package tgc.edu.ljc.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import tgc.edu.ljc.entity.Student;
import tgc.edu.ljc.entity.TbClass;
import tgc.edu.ljc.service.ClassService;
import tgc.edu.ljc.service.StudentService;

@Controller
@RequestMapping(value="/student")
public class StudentController {
	@Autowired
	private StudentService service;
	@Autowired
	private ClassService classService;
	
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String login() {
		return "student/login";
	}
	
	@RequestMapping(value="/main")
	public String main(ModelMap map) {
		map.put("students", service.findAll());
		return "student/main";
	}
	
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(String username,String password,HttpSession session) {
		Student student=service.login(username,password);
		if(student==null) {
			session.removeAttribute("user");
			return "redirect:login";
		}else {
			session.setAttribute("user", student);
			List<Student> list=service.findAll();
			return "redirect:main";
		}
	}
	
	@RequestMapping(value="/edit")
	public String edit(Integer id,ModelMap map) {
		Student model=new Student();
		if(id!=null) {
			model=service.findById(id);
		}
		map.put("model", model);
		List<TbClass> bjs = classService.findAll();
		map.put("bjs", bjs);
		return "student/edit";
	}
	
	@RequestMapping(value="/save")
	public String save(Student model) {
		service.save(model);
		return "redirect:main";
	}
}
